//
//  EventAndAnalysisViewController.m
//  LiveSoftware
//
//  Created by lanou3g on 15/7/16.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "EventAndAnalysisViewController.h"

#import "ScoreEventViewController.h"
#import "ScoreAnalysisViewController.h"

@interface EventAndAnalysisViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>


@property(nonatomic,strong)UILabel *navTitle;

@property(nonatomic,strong)ScoreTableHeaderView *headerView;

@property(nonatomic,strong)UIImageView *btnBgImage;
@property(nonatomic,strong)UIButton *eventbutton;
@property(nonatomic,strong)UIButton *analysisButton;
@property(nonatomic,strong)UIButton *pointImage;


@property(nonatomic,strong)UITableView *baseTableView;

@property(nonatomic,strong)ScoreBaseTableViewCell *baseCell;

@property(nonatomic,strong)ScoreEventViewController *scoreEventVC;
@property(nonatomic,strong)ScoreAnalysisViewController *scoreAnalysisVC;


@property(nonatomic,copy)NSString *messageData;

@property(nonatomic,copy)NSString *homeText;
@property(nonatomic,copy)NSString *awayText;


@end



@implementation EventAndAnalysisViewController

#pragma mark - ================== viewDidLoad =================
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 自定义 navigationBar
    [self customNavigationBar];
    
    // 整体大 tableView
    self.baseTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    self.baseTableView.dataSource = self;
    self.baseTableView.delegate = self;
    self.view = self.baseTableView;
    
    self.baseTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    // 设置 tableheaderView
    self.headerView = [[ScoreTableHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenIp6(100))];
    self.baseTableView.tableHeaderView = self.headerView;
    
    self.baseTableView.showsVerticalScrollIndicator = NO;
    
    
    // 先赋一个适当的cell 高度 用来占位
    self.baseTableView.rowHeight = kScreenHeight - kScreenIp6(40) - 49;
    
    self.baseCell = [self.baseTableView.visibleCells firstObject];
    self.baseCell.baseScrollView.delegate = self;
    
    
    
    // 解析数据
    [self JieXiForHomeAndAwayMessage];
    // 加载子视图
    [self loadEventAndAnalysisController];
    
    
    
    
//    self.baseTableView.backgroundColor = [UIColor redColor];
//    self.baseCell.baseScrollView.backgroundColor = [UIColor greenColor];
    
}


#pragma mark - ===================== 解析数据 =====================

#pragma mark 计算时间 便于拼接
//现在的秒数
-(NSString *)getMiaoShu
{
    
    NSDate *today = [NSDate date];
    
    double dureen = [today timeIntervalSince1970];
    
    NSString *timeString = [NSString stringWithFormat:@"%f",dureen];
    
    
    NSString* miao = [[timeString componentsSeparatedByString:@"."]objectAtIndex:0];
    NSString *haomiao = [[timeString componentsSeparatedByString:@"."]objectAtIndex:1];
    
    
    NSString *subHaomiao =[haomiao substringToIndex:3];
    
    NSString * totalTime = [NSString stringWithFormat:@"%@%@",miao,subHaomiao];
    return totalTime;
    
}


#pragma mark 解析数据
-(void)JieXiForHomeAndAwayMessage
{
    
    NSString *urlString = [NSString stringWithFormat:@"http://apk.win007.com/phone/ScheduleDetail.aspx?ID=%@&lang=0&ran=%@", self.matchID ,[self getMiaoShu ] ];
    
    NSURL *url = [NSURL URLWithString:urlString];
    
    //异步解析
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
    
    
    [urlRequest addValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
    
    [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue]completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
     {
         
         self.messageData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
         
         // headerView 赋值
         [self  divisionHomeAndAwayMessageData];
         // 加载 分析 事件 数据
         [self  loadEventAndAnalysisController];
         
     }];
    
}


#pragma mark  headerView 赋值
//分割字符串
-(void)divisionHomeAndAwayMessageData
{
    
//    NSLog(@"---------self.scoreData---%@",self.messageData);
    
    if(self.messageData != nil && self.messageData.length != 0)
    {
  
        //克林辛尼^波佩什蒂莱奥代尼^克林辛尼^萊奧爾代尼^-1^20150715160000^^^^^4^3^
        //艾马迪^艾拉斯克特^艾馬迪^艾拉斯克特^1^20150716224500^^^images/20130804165732.gif^images/20130805202917.png^0^0^
        //http://zq.win007.com/image/team/images/20130804165732.gif
        //http://zq.win007.com/image/team/images/20130805202917.png
        
    
         NSArray *first = [self.messageData componentsSeparatedByString:@"^"];
        
        for(int i= 0 ; i< first.count; i++)
        {
            
//            NSLog(@"----%@---%d",first[i],i);
        }
        
        //主队
        self.headerView.hostName.text = [[first[0] componentsSeparatedByString:@"("] firstObject];
        self.homeText = [[first[0] componentsSeparatedByString:@"("] firstObject];
        //客队
        self.headerView.guestName.text = [[first[1] componentsSeparatedByString:@"("] firstObject];
        self.awayText = [[first[1] componentsSeparatedByString:@"("] firstObject];
        
        
        
        // 比赛状态
        NSString *matchState = first[4];
        if([matchState isEqualToString:@"-1"])
        {
            self.headerView.matchState.text = @"完场";
        }
        else if([matchState isEqualToString:@"0"])
        {
            self.headerView.matchState.text = @"未开";
        }
        else
        {
            self.headerView.matchState.text = @"进行中";
        }
        
#pragma mark 如果比赛状态为 未开, 默认显示分析界面
        if ([self.headerView.matchState.text isEqualToString:@"未开"])
        {
            self.baseCell.baseScrollView.contentOffset = CGPointMake(kScreenWidth, 0);
            [self switchButtonPoint];
        }
        
        
        // 比赛时间
        NSMutableString *tempTime  = [[first[5] substringWithRange:NSMakeRange(4, 8)] mutableCopy];
        
        [tempTime insertString:@"-" atIndex:2];
        [tempTime insertString:@" " atIndex:5];
        [tempTime insertString:@":" atIndex:8];
        self.headerView.matchTime.text = tempTime;
        
        // 主队比分
        self.headerView.hostScore.text = [first objectAtIndex:first.count-3];
        // 客队比分
        self.headerView.guestScore.text  =  [first  objectAtIndex:first.count-2 ];
        
        // 图片
        NSString *urlZhu= [NSString stringWithFormat:@"http://zq.win007.com/image/team/%@",first[8]];
        [self.headerView.hostLogo setImageWithURL:[NSURL URLWithString:urlZhu] placeholderImage:[UIImage imageNamed:@"zhudui_1@2x"]];
        
        NSString *urlKe= [NSString stringWithFormat:@"http://zq.win007.com/image/team/%@",first[9]];
        [self.headerView.guestLogo setImageWithURL:[NSURL URLWithString:urlKe] placeholderImage:[UIImage imageNamed:@"kedui_2@2x"]];
        
    }
    
}



#pragma mark - ========================= 加载视图 =================


-(void)loadEventAndAnalysisController
{
    
    // 加载分析视图
    self.scoreAnalysisVC= [[ScoreAnalysisViewController alloc]init];
    
    self.scoreAnalysisVC.matchID = self.matchID;
    self.scoreAnalysisVC.homeName = self.homeText;
    self.scoreAnalysisVC.awayName = self.awayText;
    
    [self addChildViewController:self.scoreAnalysisVC];
    self.scoreAnalysisVC.tableView.frame = CGRectMake(0, 0, kScreenWidth, self.baseCell.rightView.bounds.size.height);
    [self.baseCell.rightView addSubview:self.scoreAnalysisVC.tableView];
    
    [self.scoreAnalysisVC.tableView reloadData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTableViewRowHeight) name:@"analysisFinish" object:nil];
    
    
    // 加载事件视图
    self.scoreEventVC = [[ScoreEventViewController alloc]init];
    
    self.scoreEventVC.matchID = self.matchID;
    
    [self addChildViewController:self.scoreEventVC];
    self.scoreEventVC.tableView.frame = CGRectMake(0, 0, kScreenWidth, self.baseCell.leftView.bounds.size.height);
    [self.baseCell.leftView  addSubview:self.scoreEventVC.tableView];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTableViewRowHeight) name:@"eventFinish" object:nil];
    
    
    
}



#pragma mark - 给 cell 赋不同的高度
- (void)setTableViewRowHeight
{
    if (self.baseCell.baseScrollView.contentOffset.x == 0)
    {
        self.baseTableView.rowHeight = self.scoreEventVC.tableView.contentSize.height;
    }
    else
    {
        self.baseTableView.rowHeight =  self.scoreAnalysisVC.tableView.contentSize.height;
    }
    
    // 如果高度小于一个屏幕高, 就等于屏幕高
    if (self.baseTableView.rowHeight < (kScreenHeight - 49 - kScreenIp6(40)))
    {
        self.baseTableView.rowHeight = (kScreenHeight - 49 - kScreenIp6(40));
    }
    
    
    [self.baseTableView reloadData];
    
    // 回到顶头
    [self.baseTableView setContentOffset:CGPointMake(0, 0) animated:YES];
}




#pragma mark - ================ UITableView 数据源方法 ==============

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return 1;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"baseCell";
    [tableView registerClass:[ScoreBaseTableViewCell class] forCellReuseIdentifier:cellIdentifier];
    ScoreBaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    
    
    
    return cell;
    
}




#pragma mark - ============= UITableView 代理方法 ===================

/*
#pragma mark 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
// 满屏显示的话, 返回这个
//    return kScreenHeight - 64 - kScreenIp6(40) - 49;
 
}
*/



#pragma mark headerView 的高

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return kScreenIp6(40);
}


#pragma mark 自定义 分组HeaderView
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    self.btnBgImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenIp6(40))];
    self.btnBgImage.image = [UIImage imageNamed:@"header_bg_green_2"];
    self.btnBgImage.userInteractionEnabled = YES;
    
    // 事件button
    self.eventbutton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.eventbutton setTitle:@"事件" forState:UIControlStateNormal];
    self.eventbutton.frame = CGRectMake(0, 0, kScreenWidth/2,kScreenIp6(40) );
    [self.eventbutton setTintColor:[UIColor whiteColor]];
    [self.eventbutton addTarget:self action:@selector(eventAction) forControlEvents:UIControlEventTouchUpInside];
    [self.btnBgImage addSubview:_eventbutton];
    
    // 分析 Button
    self.analysisButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.analysisButton setTitle:@"分析" forState:UIControlStateNormal];
    self.analysisButton.frame = CGRectMake(kScreenWidth/2, 0, kScreenWidth/2, kScreenIp6(40));
    [self.analysisButton setTintColor:[UIColor colorWithWhite:0.900 alpha:1.000]];
    [self.analysisButton addTarget:self action:@selector(analysisAction) forControlEvents:UIControlEventTouchUpInside];
    [self.btnBgImage addSubview:_analysisButton];
    
    
    self.pointImage = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.pointImage setImage:[UIImage imageNamed:@"point"] forState:UIControlStateNormal];
    self.pointImage.bounds = CGRectMake(0, 0, kScreenIp6(15), kScreenIp6(20));
    if (self.baseCell.baseScrollView.contentOffset.x == kScreenWidth)
    {
        self.pointImage.center = CGPointMake(kScreenWidth*3/4, kScreenIp6(36));
    }
    else
    {
        self.pointImage.center = CGPointMake(kScreenWidth/4, kScreenIp6(36));
    }
    [self.pointImage setTintColor:[UIColor whiteColor]];
    [self.btnBgImage addSubview:_pointImage];
    
        
    return self.btnBgImage;
    
    
}


// 切换 Button 指向
- (void)switchButtonPoint
{
    if (self.baseCell.baseScrollView.contentOffset.x == 0)
    {
        self.pointImage.center = CGPointMake(kScreenWidth/4, kScreenIp6(36));
        [self.eventbutton setTintColor:[UIColor whiteColor]];
        [self.analysisButton setTintColor:[UIColor colorWithWhite:0.900 alpha:1.000]];
    }
    else
    {
        self.pointImage.center = CGPointMake(kScreenWidth*3/4, kScreenIp6(36));
        [self.analysisButton setTintColor:[UIColor whiteColor]];
        [self.eventbutton setTintColor:[UIColor colorWithWhite:0.900 alpha:1.000]];
    }
}


//事件
-(void)eventAction
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelegate:self];
    
    
   self.baseCell.baseScrollView.contentOffset = CGPointMake(0, 0);
    [self switchButtonPoint];
    
    // 给 cell 赋不同的高度
    [self setTableViewRowHeight];
    
    [UIView commitAnimations];
    
}


//分析
-(void)analysisAction
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelegate:self];
    
    self.baseCell.baseScrollView.contentOffset = CGPointMake(kScreenWidth, 0);
    [self switchButtonPoint];
    
    // 给 cell 赋不同的高度
    [self setTableViewRowHeight];
    
    [UIView commitAnimations];
    
}


#pragma mark 点击 cell 的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}




#pragma mark - ----------------------------UIScrollView 代理方法




- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    if (scrollView == self.baseCell.baseScrollView)
    {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationDelegate:self];
        
        int i = (self.baseCell.baseScrollView.contentOffset.x + kScreenWidth/2)/kScreenWidth;
        self.pointImage.center = CGPointMake((i * kScreenWidth/2 + kScreenWidth/4), kScreenIp6(36));
        
        [UIView commitAnimations];
    }
    
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    
    if (scrollView == self.baseCell.baseScrollView)
    {
        
        // 切换 Button 的指向
        [self switchButtonPoint];
        
        
        // 给 cell 赋不同的高度
        [self setTableViewRowHeight];
        
    }
    
}










#pragma mark - -------------------------------- 自定义 navigationBar

- (void)customNavigationBar
{
//    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"header_bg_green_2@2x"] forBarMetrics:UIBarMetricsDefault];
    
    
    UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"set_arrow_back"] style:UIBarButtonItemStylePlain target:self action:@selector(popback)];
    [backBarButton setTintColor:[UIColor whiteColor]];
    self.navigationItem.leftBarButtonItem = backBarButton;
    
    self.navTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenIp6(50), kScreenIp6(30))];
    self.navTitle.text = self.leagueName;
    self.navTitle.textColor = [UIColor whiteColor];
    [self.navigationItem setTitleView:_navTitle];
    
    [self hiddenNavigationLine];
}


// backBarButton 的点击方法
- (void)popback
{
    [self.navigationController popViewControllerAnimated:YES];
}


// 去掉 NavigationBar 下面的黑线
- (void) hiddenNavigationLine
{
    if ([self.navigationController.navigationBar respondsToSelector:@selector( setBackgroundImage:forBarMetrics:)]){
        
        NSArray *list=self.navigationController.navigationBar.subviews;
        
        for (id obj in list) {
            
            if ([obj isKindOfClass:[UIImageView class]]) {
                
                UIImageView *imageView=(UIImageView *)obj;
                
                NSArray *list2=imageView.subviews;
                
                for (id obj2 in list2) {
                    
                    if ([obj2 isKindOfClass:[UIImageView class]]) {
                        
                        UIImageView *imageView2=(UIImageView *)obj2;
                        
                        imageView2.hidden=YES;
                        
                    }
                    
                }
                
            }
            
        }
        
    }
    
}



#pragma mark - 隐藏 tabbar
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.tabBarController.tabBar.hidden = YES;
    
    
    
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    self.tabBarController.tabBar.hidden = NO;
}
















@end
